package com.hnld.transform.handler.impl;

import cn.hutool.core.io.FileUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.hnld.transform.cosntant.TransformConstant;
import com.hnld.transform.entity.*;
import com.hnld.transform.handler.IOtherFileHandler;
import com.hnld.transform.util.CSVFileUtils;
import com.hnld.transform.util.FileTransferUtil;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

public class OtherDRFileHandler implements IOtherFileHandler {
    private static List<String> targets = Lists.newArrayList();
    private static Map<String, String> sourceMap = Maps.newHashMap();
    private static Map<String, Map<String, Class<?>>> routeTypeMap = Maps.newHashMap();

    private static String routePath = "/路面图像/";

    static {
        //
        targets.add("DR");
        targets.add("IRI");
        targets.add("LBI");
        targets.add("RIFile");
        //对应的源文件夹目录
        sourceMap.put("DR", "/路面景象/识别结果/");
        sourceMap.put("IRI", "/平整度数据/IRI/");
        sourceMap.put("LBI", "/LBI/");
        sourceMap.put("RIFile", "/平整度数据/RIFile/");
        //水泥等级
        Map<String, Class<?>> levelShuiNiMap = Maps.newHashMap();
        levelShuiNiMap.put("标准", StandShuiNiRoute.class);
        levelShuiNiMap.put("指南", LowShuiNiRoute.class);
        routeTypeMap.put("水泥路面", levelShuiNiMap);
        //沥青等级
        Map<String, Class<?>> levelLiQingMap = Maps.newHashMap();
        levelLiQingMap.put("标准", StandLiQingRoute.class);
        levelLiQingMap.put("指南", LowLiQingRoute.class);
        routeTypeMap.put("沥青路面", levelLiQingMap);
    }

    @Override
    public String getType() {
        return "DR";
    }


    @Override
    public void handleFileType(List<File> files, String targetDir, String area, String areaRuteCode, Parameter parameter, Map<String, Integer> twoDirectionsMap) {
        String routeCode = areaRuteCode.substring(0, areaRuteCode.length() - 1);//获取到不带方向的路线编码
        if (!twoDirectionsMap.isEmpty()) {
            Integer integer = Optional.ofNullable(twoDirectionsMap.get(routeCode)).orElse(0);
            //是否有两个方向
            if (integer > 1) {
                //
                files = files.stream().filter(f -> !f.getName().contains("砂石路面")).filter(f -> f.getName().startsWith(areaRuteCode)).collect(Collectors.toList());
            } else {
                files = files.stream().filter(f -> !f.getName().contains("砂石路面")).filter(f -> f.getName().startsWith(routeCode)).collect(Collectors.toList());
            }
        }

        for (File file : files) {
            handlerRoute(file, area, targetDir, areaRuteCode, parameter);
        }
    }

    private void handlerRoute(File file, String area, String targetDir, String areaRuteCode, Parameter parameter) {
        System.out.println("处理区县【" + area + "】的路线【" + areaRuteCode + "】非图像类DR数据");
        String baseSourcePath = parameter.getBaseSourcePath() + area + "\\";
        //文件名修改
        String fileName = file.getName();
        String[] DRSplit = fileName.split("-");
        //C16A431102A-(指南)水泥路面-0.000-0.100.csv -> C236320134A-DR-0.000-0.720-20230714105000.txt
        String routeCode = DRSplit[0];
        String routeType = DRSplit[1];
        //获取路面类型
        int startIndex = routeType.indexOf(")") + 1; // 找到右括号后的位置
        String route = routeType.substring(startIndex); // 提取括号外的内容
        //获取路面等级
        String extractContent = FileTransferUtil.extractContent("\\((.*?)\\)", routeType);
//        Map<String, Class<?>> routeClassMap = routeTypeMap.get(route);
//        Class<?> aClass = routeClassMap.get(extractContent);
        //时间需要从LBI中获取
        String LBIPath = baseSourcePath + TransformConstant.LBI;
        File timeFile = FileTransferUtil.getLBIFile(LBIPath, routeCode);
        if (timeFile == null) {
            System.out.println("路线" + routeCode + "的LBI文件不存在,无法确认文件名的后缀时间");
            TransformConstant.DR_ROUTE.add(routeCode);
            return;
        }
        String[] splitTime = timeFile.getName().split("-");
        String time = splitTime[splitTime.length - 1].split("\\.")[0];
        //新文件名
        String newFileName = FileTransferUtil.getNewFileName(areaRuteCode, getType(), time, DRSplit);
        writeCSVData(route, extractContent, file, targetDir + "\\" + newFileName);
    }

    private void writeCSVData(String route, String extractContent, File file, String targetPath) {
        List<String> writeContent = new ArrayList<>();
        if (route.equals("水泥路面")) {
            if (extractContent.equals("指南")) {
                //读取dr文件内容
                List<LowShuiNiRoute> csvDatas = CSVFileUtils.readCSVData(file.getPath(), LowShuiNiRoute.class, true);
                List<String> titleList = CSVFileUtils.getTitleList(LowShuiNiRoute.class, TransformConstant.excludeTitle, "识别宽度(m)", 1);
                String titleContent = String.join(",", titleList);
                writeContent.add(titleContent);
                csvDatas.forEach(data -> {
                    if (StringUtils.isBlank(data.getStake())) {
                        return;
                    }
                    //拼接内容
                    //起点桩号(km),识别宽度(m),破损率DR(%),破碎板(㎡),裂缝(m),错台(㎡),拱起(㎡),坑洞(㎡)
                    String content = String.join(",", data.getStake(), data.getEnableWidth(), data.getBadRate(),
                            data.getBadBoard(), data.getSplitLine(), data.getErrorStage(), data.getArching(), data.getPit());
                    writeContent.add(content);
                });
            } else {
                List<StandShuiNiRoute> csvDatas = CSVFileUtils.readCSVData(file.getPath(), StandShuiNiRoute.class, true);
                List<String> titleList = CSVFileUtils.getTitleList(StandShuiNiRoute.class, TransformConstant.excludeTitle, "识别宽度(m)", 1);
                String titleContent = String.join(",", titleList);
                writeContent.add(titleContent);
                csvDatas.forEach(data -> {
                    if (StringUtils.isBlank(data.getStake())) {
                        return;
                    }
                    //拼接内容
                    //起点桩号(km),识别宽度(m),破损率DR(%),破碎板(㎡),裂缝(m),板角断裂(㎡),错台(m),拱起(㎡),边角剥落(m),接缝料损坏(m),坑洞(㎡),唧泥(m),露骨(㎡),修补(㎡)
                    String content = String.join(",", data.getStake(), data.getEnableWidth(), data.getBadRate(),
                            data.getCracked(), data.getCracks(), data.getCornerFracture(), data.getCrossCracks(),
                            data.getArching(), data.getCornerSpalling(), data.getJointFillerBreak(), data.getPit(), data.getPumping(),
                            data.getBlatant(), data.getRepair());
                    writeContent.add(content);
                });
            }

        } else if (route.equals("沥青路面")) {
            if (extractContent.equals("指南")) {
                //读取dr文件内容
                List<LowLiQingRoute> csvDatas = CSVFileUtils.readCSVData(file.getPath(), LowLiQingRoute.class, true);
                List<String> titleList = CSVFileUtils.getTitleList(LowLiQingRoute.class, TransformConstant.excludeTitle, "识别宽度(m)", 1);
                String titleContent = String.join(",", titleList);
                writeContent.add(titleContent);
                csvDatas.forEach(data -> {
                    if (StringUtils.isBlank(data.getStake())) {
                        return;
                    }
                    //拼接内容
                    //起点桩号(km),识别宽度(m),破损率DR(%),网裂(㎡),纵向裂缝(m),横向裂缝(m),坑槽(㎡)
                    String content = String.join(",", data.getStake(), data.getEnableWidth(), data.getBadRate(),
                            data.getCracked(), data.getVerticalCracks(), data.getCrossCracks(), data.getPitGroove());
                    writeContent.add(content);
                });
            } else {
                List<StandLiQingRoute> csvDatas = CSVFileUtils.readCSVData(file.getPath(), StandLiQingRoute.class, true);
                List<String> titleList = CSVFileUtils.getTitleList(StandLiQingRoute.class, TransformConstant.excludeTitle, "识别宽度(m)", 1);
                String titleContent = String.join(",", titleList);
                writeContent.add(titleContent);
                csvDatas.forEach(data -> {
                    if (StringUtils.isBlank(data.getStake())) {
                        return;
                    }
                    //拼接内容
                    //起点桩号(km),识别宽度(m),破损率DR(%),龟裂(㎡),块状裂缝(㎡),纵向裂缝(m),横向裂缝(m),沉陷(㎡),车辙(m),波浪拥包(㎡),坑槽(㎡),松散(㎡),泛油(㎡),修补(㎡)
                    String content = String.join(",", data.getStake(), data.getEnableWidth(), data.getBadRate(),
                            data.getCracked(), data.getBlockCracks(), data.getVerticalCracks(), data.getCrossCracks(),
                            data.getSubsidence(), data.getRut(), data.getWaveRutting(), data.getPitGroove(), data.getLoose(),
                            data.getBleeding(), data.getRepair());
                    writeContent.add(content);
                });
            }
        }
        //写入文件
        FileUtil.writeLines(writeContent, targetPath, Charset.defaultCharset());

    }

    private static void replacesFieldValue(List<?> objects) {
      /*  objects.forEach(obj -> {
            obj.getClass().getDeclaredFields();
        })*/
    }


}
